package cn.bytecollege.controller;

import cn.bytecollege.constant.Resource;
import cn.bytecollege.entity.Room;
import cn.bytecollege.entity.RoomCategory;
import cn.bytecollege.service.RoomCategoryService;
import cn.bytecollege.service.RoomService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "RoomAddController",value = "/roomAdd")
public class RoomAddController extends HttpServlet {
    private RoomService roomService = null;
    private RoomCategoryService roomCategoryService = null;
    public RoomAddController(){
        roomService = new RoomService();
        roomCategoryService = new RoomCategoryService();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //封装分类数据
        List<RoomCategory> list = roomCategoryService.find();
        request.setAttribute("list",list);
        request.getRequestDispatcher(Resource.PAGE_LOCATION + "/roomAdd.jsp")
                .forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = null;
        HttpSession session = request.getSession();
        //1.接收请求参数
        String number = request.getParameter("number");
        String categoryId = request.getParameter("category");
        String price = request.getParameter("price");

        Integer roomNumber = Integer.valueOf(number);
        Integer roomCategoryId = Integer.valueOf(categoryId);
        Double roomPrice = Double.valueOf(price);

        List<Room> list=roomService.findRoomByRoomNumber(roomNumber);
        //如果房间不存在
        if(list.size()>0){
            msg = "该房间已经存在！";
            request.setAttribute("msg",msg);
            List<RoomCategory> list1 = roomCategoryService.find();
            request.setAttribute("list",list1);
            request.getRequestDispatcher(Resource.PAGE_LOCATION + "/roomAdd.jsp")
                    .forward(request,response);

            return;
        }
        //2.封装数据
        Room room = new Room();
        room.setRoomNumber(roomNumber);
        room.setRoomCategoryId(roomCategoryId);
        room.setRoomPrice(roomPrice);
        room.setRoomState(0);
        room.setDeleteFlag(0);
        //调用Service方法
        roomService.save(room);
        //跳转页面
        response.sendRedirect(request.getContextPath() + "/roomListAll");
    }
}
